package org.jeecg.modules.activiti.listener;

import com.alibaba.fastjson.JSON;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.modules.activiti.entity.ActBusiness;
import org.jeecg.modules.activiti.service.IActBusinessService;
import org.jeecg.modules.putstorage.entity.ZcglPutStorageAssets;
import org.jeecg.modules.putstorage.service.IZcglPutStorageAssetsService;
import org.jeecg.modules.putstorage.vo.ZcglPutStoragePage;
import org.jeecg.modules.zcgl.entity.AssetFixed;
import org.jeecg.modules.zcgl.service.IAssetFixedService;
import org.jeecg.modules.zcglRecipients.entity.ZcglRecipients;
import org.jeecg.modules.zcglRecipients.entity.ZcglRecipientsAssets;
import org.jeecg.modules.zcglRecipients.service.IZcglRecipientsService;
import org.jeecg.modules.zcglRecipients.vo.ZcglRecipientsPage;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class ZcglRecipientsListener  implements ExecutionListener {

    IActBusinessService actBusinessService;
    IAssetFixedService assetFixedService;

    IZcglRecipientsService zcglRecipientsService;

    @Override
    public void notify(DelegateExecution execution) throws Exception {
        if (actBusinessService == null) {
            actBusinessService = (IActBusinessService) SpringContextUtils.getBean("actBusinessServiceImpl");
        }
        if (zcglRecipientsService == null) {
            zcglRecipientsService = (IZcglRecipientsService) SpringContextUtils.getBean("zcglRecipientsServiceImpl");
        }
        if (assetFixedService == null) {
            assetFixedService = (IAssetFixedService) SpringContextUtils.getBean("assetFixedServiceImpl");
        }
        String eventName = execution.getEventName();
        //start
        if (EVENTNAME_START.equals(eventName)) {

        } else if (EVENTNAME_END.equals(eventName)) {
            //结束后 就减少仓库的数量就行了
            ActBusiness actBusiness = actBusinessService.getById(execution.getProcessBusinessKey());
                if (actBusiness != null && "zcgl_recipients".equalsIgnoreCase(actBusiness.getTableName())){
                    ZcglRecipientsPage page = JSON.parseObject(actBusiness.getData(), ZcglRecipientsPage.class);
                    List<ZcglRecipientsAssets> list = page.getZcglRecipientsAssetsList();
                    for (int i = 0; i < list.size(); i++) {
                       AssetFixed assetFixed = assetFixedService.getById(list.get(i).getAssetId());
                        assetFixed.setAmount(assetFixed.getAmount().subtract(list.get(i).getAssetAmount()));
                        assetFixedService.updateById(assetFixed);
                    }
                }

        }
    }
}
